import { VmErr } from "../svm/VmErr";
import { SgScript } from "../utils/SgScript";
import { BaseNode } from "./com/BaseNode";
export class ImportNode extends BaseNode {
    public nodes: BaseNode[] = []
    constructor(name?: string, val?: string) {
        super(name ? name : 'Import')
        this.edit.out = false
        this.type = 'Import'
        this.canReference = true
        this.bgColor = '#c13328'

        this.addAttribute({
            name: "path",
            value: val ? val : 'none',
            type: 'string',
            options: undefined,
            disable: true
        })
        this.addInput({ key: 'line' })
        this.onAttributeClick = this.onAttributeClickHandler.bind(this)
        this.refresh()
    }
    addAttribute(attr: NodeAttribute) {
        super.addAttribute(attr)
        if (attr.name == 'path' && attr.value != 'none' && attr.value != '') {
            this.parseData(attr.value)
        }
    }

    private async parseData(path: string) {
        const data = await window.editor.getFileContent(path)
        if (!data) {
            throw new VmErr(this.id, this.titleContent + ' file not empty,path: ' + path)
        }
        const script = await SgScript.decode(data)
        this.nodes = [...script.nodes]
        this.nodes.forEach(n => n.isImport = true)
    }

    verify(): boolean {
        const path = this.getAttribute('path')
        if (!path?.value) {
            throw new VmErr(this.id, this.titleContent + ' input or connect undefined')
        }
        return true
    }
    async onAttributeClickHandler(attr: NodeAttribute) {
        if (attr.name !== 'path') {
            return
        }
        const res = await window.editor.openFile('open script')
        if (!res.data) {
            throw new VmErr(this.id, this.titleContent + ' file not empty')
        }
        this.parseData(res.filePath)
        this.attributes[0].value = res.filePath
        this.refresh()
    }
}